import java.io.*;
import java.net.Socket;
import java.util.Scanner;

//client tcp

@SuppressWarnings("all")
public class TCPClient {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);

        // 创建client
        //初始化连接服务器ServerSocket
        System.out.print("please input server inet4 address:");
        String serverAddress = scanner.nextLine();
        Socket socket = new Socket(serverAddress,8888);
        System.out.println("server connection succeeded!\n");

        OutputStream outputStream = null;
        InputStream inputStream = null;
        while(true){
            // 向server发送信息
            outputStream = socket.getOutputStream();
            // 字符流
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            // 输入内容
            System.out.print("client> ");
            String input = scanner.nextLine();
            if("exit".equals(input)){
                break;
            }
            bufferedWriter.write(input);
            bufferedWriter.newLine(); // 插入一个换行符，表示写入的内容结束 要求对方使用readLine()
            bufferedWriter.flush();  // 使用字符流，需要手动刷新，否者数据不会写入

            // 接收server信息
            inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String output = bufferedReader.readLine();
            System.out.println(output);



        }

        inputStream.close();
        outputStream.close();
        socket.close();

        System.out.println("\nclient has exited.");

    }
}
